<template>
  <div>
    <!-- 先注释，以后可能用到 -->
    <!-- <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form ref="form" :model="form" label-width="80px" :inline="true">
          <el-form-item label="登录地址">
            <el-input></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="btn-search"
              round
              icon="el-icon-search"
              size="medium"
              >搜索</el-button
            >
            <el-button
              class="btn-search"
              round
              icon="el-icon-refresh"
              size="medium"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </card-search>
    </el-collapse-transition> -->
    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="
              isSuperAdmin || hasPermission('monitor:online:batchForceLogout')
            "
            class="btn-search"
            size="small"
            :disabled="btnDisabled"
            @click="handleClick(null, 'logout')"
            ><svg-icon icon-class="logout" style="margin-right: 5px"></svg-icon
            >强退</el-button
          >

          <el-input
            v-if="isSuperAdmin || hasPermission('monitor:online:list')"
            v-model="input"
            placeholder="请输入登录名称"
            style="width: 450px; margin-left: 10px"
            clearable
            size="small"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :table-header="tableHeader"
            :eye-show="false"
            :search-show="false"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="filteredTableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        size="small"
        stripe
        :default-sort="{ prop: 'date', order: 'descending' }"
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        highlight-selection-row
        border
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="checkSelectable"
        />
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          :show-overflow-tooltip="true"
          :align="item.align"
          sortable
        >
          <template #default="scope">
            <span v-if="item.prop === 'status'" class="link-type">
              <span
                style="color: #1ab394"
                v-if="scope.row[item.prop] === 'on_line'"
                >在线</span
              ><span style="color: #ed5565" v-else>离线</span>
            </span>
            <span v-else>
              {{ scope.row[item.prop] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </card-table>
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
import {
  onlineList,
  onlineForceLogoutSingle,
  onlineForceLogoutMore,
} from "@/api/MonitorManagement";
export default {
  components: {
    CardSearch,
    CardTable,
    TableAction,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      input: "",
      tableHeight: 550,
      tableHeader: [
        {
          title: "会话编号",
          prop: "sessionId",
          width: "200",
          visible: true,
          align: "center",
        },
        {
          title: "登录名称",
          prop: "loginName",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "部门名称",
          prop: "deptName",
          width: "150",
          visible: true,
          align: "center",
        },
        {
          title: "主机",
          prop: "ipaddr",
          width: "150",
          visible: true,
          align: "center",
        },
        {
          title: "登录地点",
          prop: "loginLocation",
          width: "150",
          visible: true,
          align: "center",
        },
        {
          title: "浏览器",
          prop: "browser",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "操作系统",
          prop: "os",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "状态",
          prop: "status",
          width: "80",
          visible: true,
          align: "center",
        },
        {
          title: "登录时间",
          prop: "startTimestamp",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "最后访问时间",
          prop: "lastAccessTime",
          width: "120",
          visible: true,
          align: "center",
        },
      ],
      tableData: [],
      multipleSelection: [],
      btnDisabled: true,
      currentPage: 1,
      pageSize: 20,
      total: 100,
    };
  },
  computed: {
    // 添加计算属性用于过滤数据
    filteredTableData() {
      if (!this.input) {
        return this.tableData; // 如果没有搜索关键字，返回所有数据
      }
      return this.tableData.filter(
        (item) => item.loginName && item.loginName.includes(this.input)
      );
    },
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.initTable();
  },
  methods: {
    initTable() {
      onlineList().then((res) => {
        this.tableData = res.data;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
    },
    checkSelectable(row, index) {
      // 禁止选择 loginName 为 admin 的用户
      return row.loginName !== "admin";
    },
    extractTokens(array) {
      return array.map((item) => item.sessionId).join(",");
    },
    handleClick(row, field) {
      switch (field) {
        case "logout":
          this.$confirm(
            `确认要强制选中的${this.multipleSelection.length}个用户下线吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            let tokens = this.extractTokens(this.multipleSelection);
            let data = {};
            if (this.multipleSelection.length == 1) {
              data.token = this.multipleSelection[0].sessionId;
              onlineForceLogoutSingle(data).then((res) => {
                if (res.code == 0) {
                  this.initTable();
                  this.$message({
                    type: "success",
                    message: "强退成功!",
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg,
                  });
                }
              });
            } else {
              data.tokens = this.extractTokens(this.multipleSelection);
              onlineForceLogoutMore(data).then((res) => {
                if (res.code == 0) {
                  this.initTable();
                  this.$message({
                    type: "success",
                    message: "强退成功!",
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg,
                  });
                }
              });
            }
          });
          break;
        default:
          break;
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.input = "";
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        console.log(
          this.$refs.multipleTable.$el,
          this.$refs.multipleTable.$el?.parentElement
        );
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
